'use client';

import { useState } from 'react';
import { TripWithDetails } from '@/types/prisma';

type ShareSettingsProps = {
  trip: TripWithDetails;
};

export function ShareSettings({ trip }: ShareSettingsProps) {
  const [isPublic, setIsPublic] = useState(trip.isPublic);
  const [shareCode, setShareCode] = useState(trip.shareCode);
  const [isLoading, setIsLoading] = useState(false);

  const handleTogglePublic = async () => {
    setIsLoading(true);
    try {
      const response = await fetch(`/api/trips/${trip.id}/share`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          isPublic: !isPublic,
        }),
      });

      if (!response.ok) throw new Error('更新失败');

      const data = await response.json();
      setIsPublic(data.isPublic);
      setShareCode(data.shareCode);
    } catch (error) {
      console.error('Failed to update sharing settings:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const shareUrl = shareCode 
    ? `${window.location.origin}/trips/shared/${shareCode}`
    : null;

  return (
    <div className="bg-white rounded-lg shadow p-6">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h3 className="text-lg font-medium">分享设置</h3>
          <p className="text-sm text-gray-500">控制谁可以查看你的行程</p>
        </div>
        <button
          onClick={handleTogglePublic}
          disabled={isLoading}
          className={`relative inline-flex flex-shrink-0 h-6 w-11 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 ${
            isPublic ? 'bg-blue-600' : 'bg-gray-200'
          }`}
        >
          <span className="sr-only">启用分享</span>
          <span
            className={`pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow transform ring-0 transition ease-in-out duration-200 ${
              isPublic ? 'translate-x-5' : 'translate-x-0'
            }`}
          />
        </button>
      </div>

      {isPublic && shareUrl && (
        <div className="mt-4">
          <label className="block text-sm font-medium text-gray-700">
            分享链接
          </label>
          <div className="mt-1 flex rounded-md shadow-sm">
            <input
              type="text"
              readOnly
              value={shareUrl}
              className="flex-1 min-w-0 block w-full px-3 py-2 rounded-md border border-gray-300 bg-gray-50"
            />
            <button
              onClick={() => {
                navigator.clipboard.writeText(shareUrl);
              }}
              className="ml-3 inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700"
            >
              复制链接
            </button>
          </div>
        </div>
      )}
    </div>
  );
} 